<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/16
 * Time: 15:50
 */
namespace Services;

use Admin\Models\group\XhsysGroup;
use Admin\Models\group\XhsysGroupuser;
use Admin\Models\school\XhschoolAutoclasserror;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysPower;
use Admin\Models\user\UserOnline;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserpower;
use Helpers\Tool;
use Helpers\Main;
use Helpers\HttpClient;
use Helpers\UserPower;
use Helpers\XhException;
use Phalcon\Mvc\Controller as PhalconController;


class UserManage extends PhalconController
{

    /**
     * @var \Helpers\HttpClient
     */
    public static $httpClient;
    public static $url;

    public $userEnum = [
        'bDisable'  => [0 => '否', 1 => '是'],
        'bHistory'  => [0 => '否', 1 => '是'],
        'bCompany'  => [0 => '否', 1 => '是'],
        'iUserSex'  => [0 => '未知', 1 => '男', 2 => '女']
    ];
    /**
     * 初始化配置
     *
     * @throws \Exception
     *
     * create by ck 20180507
     */
    private static function init()
    {
        if (!self::$httpClient) {
            $config     = Main::getConfigByName('user');
            self::$url  = Tool::getValue($config, 'url');
            if (!self::$url) {
                throw new \Exception('用户服务url获取失败');
            }
            self::$httpClient = new HttpClient(self::$url);
        }
    }

    /**
     * 更改姓名
     *
     * @param $userId
     * @param $userName
     * @return bool
     * @throws XhException
     *
     * create by ck 20180724
     */
    public static function changeName($userId, $userName)
    {
        self::init();
        $response = self::$httpClient->post(
            sprintf('/api/v1/users/%d/nameChanged?userName=%s', $userId, urlencode($userName))
        );
        if (!$response->isSuccess()) {
            throw new XhException('姓名更改失败', $response);
        }
        return true;
    }

    /**
     * 根据家长id获取绑定学生信息
     *
     * @param $parentId
     * @throws XhException
     * @return array|bool|mixed|\stdClass
     *
     * create by ck 20180709
     */
    public static function getAssociationByParent($parentId)
    {
        self::init();
        $response = self::$httpClient->get(sprintf('/api/v1/users/%d/associations/children/', $parentId));
        if (!$response->isSuccess()) {
            throw new XhException('获取关联学生失败', $response);
        }
        return $response->toArray();
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     * @param $userType
     * @param $schoolId
     * @param $normal
     * @param $status
     * @param $startDate
     * @param $endDate
     * @param $searchArr
     * @return array
     *
     * create by fyh 20181214
     * modify by fyh 20190123   新增身份证号码搜索
     */
    public function getDgData($userType, $schoolId, $normal, $status, $startDate, $endDate, $searchArr)
    {
        $parameters = [
            'columns'    => 'iUserId,sLogonName,sUserName,iPoorLevel,sAdClsName,sSelfPhone,iUserType,
            iUserSex,bDisable,bHistory,tCreateDate,iSchoolId',
            'conditions' => 'bDelete = 0 AND sLogonName <> "admin"'
        ];
        if ($userType != '') {
            $parameters['conditions'] .= " AND iUserType = {$userType}";
        }
        if ($schoolId) {
            $parameters['conditions'] .= " AND iSchoolId = {$schoolId}";
        }
        if ($normal == 'true') {
            $parameters['conditions'] .= " AND bDisable = 0 AND bHistory = 0";
        }
        if ($startDate) {
            $parameters['conditions'] .= " AND tCreateDate >= '{$startDate}'";
        }
        if ($endDate) {
            $parameters['conditions'] .= " AND tCreateDate <= '{$endDate}'";
        }
        switch ($status) {
            case 1:
                $parameters['conditions'] .= " AND bCompany = 0 AND bDisable = 0 AND bHistory = 0";
                break;
            case 2:
                $parameters['conditions'] .= " AND bHistory = 1";
                break;
            case 3:
                $parameters['conditions'] .= " AND bDisable = 1";
                break;
            case 4:
                $parameters['conditions'] .= " AND bCompany = 1";
                break;
        }
        Main::runSearchVagueConditions($parameters['conditions'], ['iUserId', 'sLogonName',
            'sUserName', 'sSelfPhone', 'sAdClsName', 'sIdentityCode'], $searchArr);
        $data = Main::runModelPage('\\Admin\\Models\\user\\XhsysUser', $parameters, $this->getUserEnum());
        Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
        return $data;
    }

    public function getUserEnum()
    {
        $this->userEnum['iUserType'] = XhsysEnum::getEnumByNodeName('用户类型');
        $this->userEnum['iGradeCode'] = XhsysEnum::getEnumByNodeName('年级');
//        $this->userEnum['iSchoolId']  = ['' => '--请选择--'] + XhschoolInfo::getSchoolSupportArray();
        return $this->userEnum;
    }

    /**
     * 根据用户id获取信息
     * @param $id
     * @return XhsysUser|array|\Phalcon\Mvc\Model
     * @throws XhException
     *
     * create by fyh 20181214
     */
    public static function getUserInfo($id)
    {
        $user = XhsysUser::findFirst($id);
        if (!$user) {
            throw new XhException('该账号不存在');
        }
        $user = $user->toArray();
        $user['sLogonPwd'] = '';
        return $user;
    }

    /**
     * 插入，修改数据
     * @param $data
     * @param $sLogonName
     * @throws XhException
     *
     * create by fyh 20181214
     */
    public static function modifyUser($data, $sLogonName)
    {
        $user = XhsysUser::createRecord($data);
        $new  = $user->iUserId ? false : true;
        if (!UserPower::checkUserPower($new ? 'User_UserList_Add' : 'User_UserList_Edit')) {
            throw new XhException('无操作权限');
        }
        if ($new && XhsysUser::count("sLogonName = '{$sLogonName}' AND bDelete = 0")) {
            throw new XhException('该账号已存在');
        }
        if ($new ? !$user->insertAfterOld() : !$user->saveWithOldData()) {
            throw new XhException('操作失败');
        }
    }

    /**
     * 根据传入id字符串，根据逗号分割后删除记录
     * @param $ids
     * @throws XhException
     *
     * create by fyh 20181214
     */
    public static function delUser($ids)
    {
        if (!XhsysUser::deleteRecord('iUserId', $ids)) {
            throw new XhException('删除失败');
        }
    }

    /**
     * 设置用户状态（启用/禁用）
     * @param $statusCondition
     * @param $ids
     * @throws XhException
     *
     * create by fyh 20181214
     */
    public function setUserState($statusCondition, $ids)
    {
        $result = $this->modelsManager->executeQuery("UPDATE \\Admin\\Models\\user\\XhsysUser SET {$statusCondition} WHERE iUserId IN ({$ids})");
        if (!$result) {
            throw new XhException('操作失败');
        }
    }

    /**
     * @param $userId
     * @param $view
     * @return mixed
     *
     * create by fyh 20181214
     */
    public static function userSetPower($userId, $view)
    {
        $groupIds = XhsysGroupuser::find([
            'columns'    => 'iGroupId AS groupId',
            'conditions' => 'bDelete = 0 AND iUserId = :userId:',
            'bind'       => ['userId' => $userId]
        ])->toArray();
        if ($groupIds) {
            $groupIds = array_column($groupIds, 'groupId');
            $groups = XhsysGroup::find([
                'columns' => 'iGroupId,sName,iType',
                'conditions' => 'bDelete = 0 AND iGroupId IN ({groupIds:array})',
                'bind' => ['groupIds' => $groupIds]
            ])->toArray();
            Tool::runEnum($groups, ['iType' => XhsysEnum::getEnumByNodeName('用户组')]);
            $data['groups'] = $groups;
        } else {
            $data['groups'] = '';
        }
        $powerTree = XhsysPower::createPowerTree(null, null, $userId, $view);
        $data['powerTree'] = $powerTree;
        return $data;
    }

    /**
     * 设置用户权限
     * @param $userId
     * @param $powerTags
     * @throws \Exception
     *
     * create by fyh 20181214
     */
    public static function setUserPower($userId, $powerTags)
    {
        $power = XhsysUserpower::findFirst([
            'conditions' => 'bDelete = 0 AND iUPUserId = :userId:',
            'bind'       => ['userId' => $userId]
        ]);
        if (!$power) {
            $power = new XhsysUserpower(['iUPUserId' => $userId]);
        }
        $power->mUPowerTag = implode(',', $powerTags);
        if (!$power->save()) {
            throw new \Exception($power->getError());
        }
    }

    /**
     * 设置为历史账号
     * @param $userIds
     * @param $history
     * @throws \Exception
     *
     * create by fyh 20181214
     */
    public function setHistory($userIds, $history)
    {
        $result = $this->modelsManager->
        executeQuery("update \\Admin\\Models\\user\\XhsysUser set bHistory = :history: where bHistory = :oldHistory: AND iUserId in ({ids:array})", [
            'ids' => $userIds, 'history' => $history, 'oldHistory' => !$history]);
        if (!$result) {
            throw new \Exception('设置失败');
        }
    }

    /**
     * 获取在线
     * @return array
     *
     * create by fyh 20181214
     */
    public static function getOnline()
    {
        $params = [
            'conditions' => '',
            'order' => 'updateTime desc'
        ];
        Main::runSearchVagueConditions($params['conditions'], [
            'logonName', 'userName', 'pageTitle', 'pageUrl', 'ip', 'browser', 'os']);
        $data = Main::runModelPage('\\Admin\\Models\\user\\UserOnline', $params);
        $time = time() - 30*60;
        foreach ($data['rows'] as &$row) {
            if ($row['updateTime'] > $time) {
                $row['status'] = '<div class="grid-cell-text-bg-green">在线</div>';
            } else {
                $row['status'] = '<div class="grid-cell-text-bg-gray">离线</div>';
            }
        }
        Tool::runTimestamp($data['rows'], 'updateTime');
        //获取当前在线人数
        $onlineCount = UserOnline::count([
            'conditions' => 'updateTime > :time:',
            'bind' => ['time' => $time]
        ]);
        $data['footer'][] = ['status' => '当前在线:', 'logonName' => $onlineCount];
        return $data;
    }

    /**
     * 获取用户登录日志
     * @param $userId
     * @param string $startDate
     * @param string $endDate
     * @return array
     */
    public static function getLogin($userId, $startDate = '', $endDate = '')
    {
        $parameters = [
            'columns'    => 'lo_processor,lo_model,lo_computername,lo_mac,lo_ip,lo_date',
            'conditions' => 'lo_us_id = :userId:',
            'bind' =>['userId' => $userId],
            'order'   => 'lo_date desc',
        ];
        if ($startDate) {
            $parameters['conditions'] .= " AND lo_date >= :startDate:";
            $parameters['bind'] = array_merge(array('startDate' => $startDate), $parameters['bind']);
        }
        if ($endDate) {
            $parameters['conditions'] .= " AND lo_date <= :endDate:";
            $parameters['bind'] = array_merge($parameters['bind'], array('endDate' => $endDate));
        }
        $data = Main::runModelPage('\\Admin\\Models\\log\\LoginLog', $parameters);
        return $data;
    }

    /**
    * 修改学校
    * @param $data
    * @throws XhException
    *
    * create by fyh 20181214
    */
    public static function modifySchool($data)
    {
        $user = XhsysUser::findFirst([
            'conditions' => 'iUserId = :iUserId: AND bDelete = 0',
            'bind'       => ['iUserId' => $data['iUserId']],
        ]);
        $user->iSchoolId = $data['iSchoolId'];
        $user->save();
    }

    //以下这些方法暂时不需要了
    /**
     * 取消学生-家长关联
     *
     * @param $parentId
     * @param $studId
     * @throws XhException
     * @return array|bool|mixed|\stdClass
     *
     * create by ck 20180709
     */
//    public static function delAssociation($parentId, $studId)
//    {
//        self::init();
//        $response = self::$httpClient->delete(
//            sprintf('/api/v1/users/%d/associations/', $parentId),
//            ['studentId' => $studId]
//        );
//        if (!$response->isSuccess()) {
//            throw new XhException('取消关联失败', $response);
//        }
//        return true;
//    }

    /**
     * 初始化学生班级
     *
     * @param $schoolId
     * @param $classInfo    --['className' => ['studId']]
     * @param $type         --0=行政班，1=培优班
     *
     * create by ck 20180711
     * modify by ck 20180712    可添加培优班
     * modify by ck 20180725    添加分组
     */
//    public static function initStudClass($schoolId, $classInfo, $type = 0)
//    {
//        try {
//            $classList  = self::getClass($schoolId);
//            $existClass = $existFolder = [];
//            foreach ($classList as $class) {
//                if ($class['type'] == $type) {
//                    if ($class['folder'] == false) {
//                        $existClass[$class['id']] = $class['abbr'];
//                    } else {
//                        $existFolder[$class['id']] = $class['abbr'];
//                    }
//                }
//            }
//
//            foreach ($classInfo as $className => $studIds) {
//                //不存在班级则创建
//                $classId  = array_search($className, $existClass);
//                $folderId = 0;
//                if (!$classId) {
//                    try {
//                        $level      = substr($className, 0, 2);
//                        $enrollYear = '20' . $level;
//
//                        //行政班不存在分组则创建
//                        if ($type == 0) {
//                            try {
//                                $folderName = $level . '级学生组';
//                                $folderId   = array_search($folderName, $existFolder);
//                                if (!$folderId) {
//                                    $folder = self::createFolder($schoolId, $folderName, $enrollYear);
//                                    $folderId = $folder['id'];
//                                    $existFolder[$folderId] = $folderName;
//                                }
//                            } catch (XhException $e) {
//                                (new XhschoolAutoclasserror())->create([
//                                    'type' => 5,
//                                    'schoolId' => $schoolId,
//                                    'className' => $className,
//                                    'classType' => $type,
//                                    'msg' => $e->getMessage(),
//                                    'description' => $e->getDescription(true),
//                                ]);
//                                continue;
//                            }
//                        }
//
//                        $class = self::createClass($schoolId, $className, $enrollYear, $type, $folderId);
//                        $classId = $class['id'];
//                    } catch (XhException $e) {
//                        (new XhschoolAutoclasserror())->create([
//                            'type' => 1,
//                            'schoolId' => $schoolId,
//                            'className' => $className,
//                            'classType' => $type,
//                            'folderId' => $folderId,
//                            'studIds' => $studIds,
//                            'msg' => $e->getMessage(),
//                            'description' => $e->getDescription(true),
//                        ]);
//                        continue;
//                    }
//                }
//
//                //添加学生到行政班
//                try {
//                    self::addClassMember($schoolId, $classId, $studIds);
//                } catch (XhException $e) {
//                    (new XhschoolAutoclasserror())->create([
//                        'type' => 3,
//                        'schoolId' => $schoolId,
//                        'className' => $className,
//                        'classId' => $classId,
//                        'classType' => $type,
//                        'studIds' => json_encode($studIds),
//                        'msg' => $e->getMessage(),
//                        'description' => $e->getDescription(true),
//                    ]);
//                    continue;
//                }
//            }
//        } catch (XhException $e) {
//            (new XhschoolAutoclasserror())->create([
//                'type' => 4,
//                'schoolId' => $schoolId,
//                'msg' => $e->getMessage(),
//                'description' => $e->getDescription(true),
//            ]);
//        }
//    }

    /**
     * 初始化教师班级
     *
     * @param $schoolId
     * @param $tchClass --['tchId'=>1,'subject'=>'语文','classNames'=>['1801']]
     *
     * create by ck 20180713
     */
//    public static function initTchClass($schoolId, $tchClass)
//    {
//        try {
//            $classList  = self::getClass($schoolId);
//            $subjectEnum= ResBase::getDictionaries('subject');
//            $existClass = [];
//            foreach ($classList as $class) {
//                if ($class['type'] == 0) {
//                    $existClass[$class['id']] = $class['abbr'];
//                }
//            }
//
//            foreach ($tchClass as $info) {
//                foreach ($info['classNames'] as $className) {
//                    $classId = array_search($className, $existClass);
//                    if (!$classId) {
//                        continue;
//                    }
//
//                    //判断科目是否存在
//                    $subject = array_search($info['subject'], $subjectEnum);
//                    if (!$subject) {
//                        continue;
//                    }
//
//                    //加入行政班
//                    try {
//                        self::addClassTch($schoolId, $classId, $info['tchId'], $subject);
//                    } catch (XhException $e) {
//                        (new XhschoolAutoclasserror())->create([
//                            'type' => 2,
//                            'schoolId' => $schoolId,
//                            'className' => $className,
//                            'classId' => $classId,
//                            'classType' => 0,
//                            'tchId' => $info['tchId'],
//                            'subject' => $info['subject'],
//                            'msg' => $e->getMessage(),
//                            'description' => $e->getDescription(true),
//                        ]);
//                        continue;
//                    }
//                }
//            }
//        } catch (XhException $e) {
//            (new XhschoolAutoclasserror())->create([
//                'type' => 4,
//                'schoolId' => $schoolId,
//                'msg' => $e->getMessage(),
//                'description' => $e->getDescription(true),
//            ]);
//        }
//    }

    /**
     * 根据学校id获取行政班
     *
     * @param $schoolId
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180710
     */
//    public static function getClass($schoolId)
//    {
//        self::init();
//        $response = self::$httpClient->get(sprintf('/api/v1/schools/%d/classes/', $schoolId));
//        if (!$response->isSuccess()) {
//            throw new XhException('获取行政班列表失败', $response);
//        }
//        return $response->toArray();
//    }

    /**
     * 创建行政班
     *
     * @param $schoolId
     * @param $name
     * @param $enrollYear
     * @param $type
     * @param $folderId
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180710
     * modify by ck 20180725    支持放入分组
     */
//    public static function createClass($schoolId, $name, $enrollYear, $type = 0, $folderId = 0)
//    {
//        self::init();
//        $response = self::$httpClient->postJson(sprintf('/api/v1/schools/%d/classes/', $schoolId), [
//            'name'          => strval($name),
//            'type'          => $type ? 'PEIYOU' : 'CLASSIC',
//            'enrollYear'    => intval($enrollYear),
//            'abbr'          => strval($name),
//            'description'   => '',
//            'folder'        => false,
//            'number'        => 0,
//            'parentId'      => $folderId,
//        ]);
//        if (!$response->isSuccess()) {
//            throw new XhException('创建班级失败', $response);
//        }
//        return $response->toArray();
//    }

    /**
     * 创建行政班分组
     *
     * @param $schoolId
     * @param $name
     * @param $enrollYear
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180725
     */
//    public static function createFolder($schoolId, $name, $enrollYear)
//    {
//        self::init();
//        $response = self::$httpClient->postJson(sprintf('/api/v1/schools/%d/classes/', $schoolId), [
//            'name'          => strval($name),
//            'enrollYear'    => intval($enrollYear),
//            'abbr'          => strval($name),
//            'description'   => '',
//            'folder'        => true,
//            'number'        => 0,
//            'parentId'      => 0,
//        ]);
//        if (!$response->isSuccess()) {
//            throw new XhException('创建分组失败', $response);
//        }
//        return $response->toArray();
//    }

    /**
     * 加入学生到行政班
     *
     * @param $schoolId
     * @param $classId
     * @param $studIds
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by ck 20180711
     */
//    public static function addClassMember($schoolId, $classId, $studIds)
//    {
//        self::init();
//        $response = self::$httpClient->postJson(
//            sprintf('/api/v1/schools/%d/classes/%d/members/', $schoolId, $classId),
//            $studIds
//        );
//        if (!$response->isSuccess()) {
//            throw new XhException('学生加入班级失败', $response);
//        }
//        return true;
//    }

    /**
     * 加入教师到行政班
     *
     * @param $schoolId
     * @param $classId
     * @param $tchId
     * @param $subject
     * @return bool
     * @throws XhException
     *
     * create by ck 20180713
     */
//    public static function addClassTch($schoolId, $classId, $tchId, $subject)
//    {
//        self::init();
//        $response = self::$httpClient->postJson(
//            sprintf('/api/v1/schools/%d/classes/%d/teachers/import', $schoolId, $classId),
//            ['subject' => strval($subject), 'teacherId' => $tchId]
//        );
//        if (!$response->isSuccess()) {
//            throw new XhException('教师加入班级失败', $response);
//        }
//        return true;
//    }

    /**
     * 强制修改用户密码（自动刷新登陆缓存）
     *
     * @param $userIds
     * @param $password
     * @param bool $alreadyMd5
     * @param bool $resetComplete
     * @return bool
     * @throws XhException
     * @throws \Exception
     *
     * create by ck 20180825
     */
//    public static function resetPassword($userIds, $password, $alreadyMd5 = false, $resetComplete = false)
//    {
//        if (!$userIds) {
//            throw new XhException('缺少用户id');
//        }
//        $userIds = is_array($userIds) ? $userIds : [$userIds];
//        self::init();
//        $password = $alreadyMd5 ? strtoupper($password) : strtoupper(md5($password));
//        $response = self::$httpClient->putJson('/api/v1/users/password/force/reset', [
//            'userIds'       => implode(',', $userIds),
//            'newPassword'   => $password,
//            'isResetStudentComplete' => $resetComplete
//        ]);
//        if (!$response->isSuccess()) {
//            throw new XhException('修改密码失败', $response);
//        }
//        return true;
//    }

}